package com.ouman.luoliluoli;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ouman.luoliluoli.utils.ThemeChanger;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import static android.widget.Toast.LENGTH_SHORT;

public class NewsDetailActivity extends AppCompatActivity {

    private int newsId;
    private String body;
    private String title;
    private String imageUrl;

    private WebView webViewBody;
    private String cssString = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ThemeChanger.applyTheme(this, null);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_news_detail);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        getSupportActionBar().setTitle("");


        Bundle bundle = this.getIntent().getExtras();
        newsId = bundle.getInt("newsId");
        System.out.println(newsId);
        new Thread(getNewsDetailThread).start();

        webViewBody = (WebView) findViewById(R.id.webViewBody);
        webViewBody.getSettings().setJavaScriptEnabled(true);
        //!!设置跳转的页面始终在当前WebView打开
        webViewBody.setWebViewClient(new WebViewClient());


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == android.R.id.home) {
            NewsDetailActivity.this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //处理网络请求，获取新闻详情
    private  Thread getNewsDetailThread = new Thread(){
        public void run(){

            HttpURLConnection connection = null;
            try {
                String urlAPI = "http://news-at.zhihu.com/api/4/news/" + newsId;
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();

                    JSONObject jsonObject = new JSONObject(result);
                    body = jsonObject.getString("body");
                    JSONArray cssArray = jsonObject.getJSONArray("css");

                    for (int i=0; i < cssArray.length(); i++){
                        cssString += "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + cssArray.get(i).toString() + "\">";
                        System.out.println("css: " + cssString);
                    }
                    System.out.println("css: " + cssString);

                    // TODO: 还是用webview显示显示html把
                    title = jsonObject.getString("title");
                    imageUrl = jsonObject.getString("image");

                    System.out.println(title);
                    if (title != null){
                        Message msg = Message.obtain();
                        msg.what = 0;
                        getNewsDetailHandler.sendMessage(msg);
                    }
                }

            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };

    private Handler getNewsDetailHandler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){

                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_news_detail);
                setSupportActionBar(toolbar);
                getSupportActionBar().setTitle(title);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);

                ImageView barImageView = (ImageView) findViewById(R.id.newsDetailAppBarImage);
                Glide.with(NewsDetailActivity.this)
                        .load(imageUrl)
                        .into(barImageView);

                // TODO 用webview的话就没有必须要解析html了
//                webViewBody.loadData(body, "text/html; charset=utf-8",null);
                // 拼接css <link rel="stylesheet" type="text/css" href="http://news-at.zhihu.com/css/news_qa.auto.css?v=4b3e3">
                System.out.println(cssString + body);
                webViewBody.loadDataWithBaseURL(null, cssString + body,
                        "text/html", "UTF-8", null);


            }else {
                Toast.makeText(NewsDetailActivity.this, "加载失败，出现位置错误", LENGTH_SHORT).show();
            }
        }
    };



}
